using System;
using Cysharp.Threading.Tasks;
using MoonFramework.FSM;
using Tool.Name;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Entity.Monster.State
{
    public class MonsterIdleState : IdleState, IMonster
    {
        public Monster Monster => _actor as Monster;
        
        public override void Enter()
        {
            base.Enter();
            Idle().Forget();
        }

        protected virtual async UniTask Idle()
        {
            await UniTask.Delay(TimeSpan.FromSeconds(Random.Range(0, 6f))); //随机休息0 - 6s
            try
            {
                if (!_actor.viewController.gameObject.activeSelf) return;
                if (Random.Range(0, 30) == 0) _actor.viewController.PlayAudio(MonsterAudioName.Idle, 0.5f);
                _actor.viewController.targetDir = Monster.MonsterObject.GetAIRandomPoint(Monster.MonsterObject.MapVertexType); //获取一个导航坐标
                _actor.fsmMachine.ChangeState(nameof(MonsterWalkState));
                Monster.MonsterObject.NavMeshAgent.enabled = true;
                Monster.MonsterObject.NavMeshAgent.SetDestination(_actor.viewController.targetDir);
            }
            catch
            {
                //防止物体已经卸载但是异步任务没有结束
            }
        }
    }
}